const express = require("express");
const router = express.Router();

const articleDB = require("../../schemas/article");

// 新增文章
router.post("/addArticle", async (req, res) => {
  const { title, description, content } = req.body;
  console.log(content);
  if (!title || !description || !content) {
    return res.send({
      code: 1,
      txt: "文章创建失败",
    });
  }

  let data = await articleDB.find();

  console.log(data);

  await articleDB.create({
    title,
    description,
    content,
    author: "猪猪侠",
    date: Date.now(),
    rank: data.length + 1,
  });

  res.send({ code: 0, txt: "文章上传成功" });
});

// 删除文章
router.post("/deleteArticle", async (req, res) => {
  const { _id } = req.body;

  const data = await articleDB.find();

  const deleteIndex = data.find((item) => item._id.toString() === _id);

  let reviseArr = data.filter((item) => item.rank > deleteIndex.rank);

  reviseArr.forEach(async (item) => {
    await articleDB.findByIdAndUpdate(
      { _id: item._id },
      { rank: item.rank - 1 }
    );
  });


  await articleDB.findByIdAndDelete({ _id });

  res.send({ code: 0, txt: "删除成功" });
});

// 获取文章
router.get("/articleList", async (req, res) => {
  const { pageSize, currentPage } = req.query;
  let data = await articleDB.find();

  const total = data.length;

  // data.sort((a, b) => a.date - b.date);

  data = data.splice((currentPage - 1) * pageSize, pageSize);

  // console.log(data);
  data.sort((a, b) => {
    return a.rank - b.rank;
  });

  res.send({
    code: 0,
    total,
    data,
  });
});

// 修改排名
router.post("/reviseRank", async (req, res) => {
  const { man, woman } = req.body;

  let manRank = man.rank;
  let womanRank = woman.rank;

  await articleDB.findByIdAndUpdate({ _id: man._id }, { rank: womanRank });
  await articleDB.findByIdAndUpdate({ _id: woman._id }, { rank: manRank });

  res.send({
    code: 0,
    txt: "排序成功",
  });
});

module.exports = router;
